﻿namespace EyeOpen.Windows.Form
{
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Drawing;
	using System.Linq;
	using System.Windows.Forms;
	using EyeOpen.Linq;
	using IContainer = EyeOpen.IContainer;

	public class FormSerializer
	{
		private readonly IContainer container;

		public FormSerializer(IContainer container)
		{
			this.container = container;
		}

		public IEnumerable<ControlSerialized> Save(Control control)
		{
			return
				control
					.Controls
					.OfType<Control>()
					.Traverse(c => c.Controls.OfType<Control>())
					.Where(c => container.Resolve<IObjectSerializer>(c) != null)
					.Select(c => container.Resolve<IObjectSerializer>(c).Save(c));
		}

		public void Load(Control control, IEnumerable<ControlSerialized> objectSerializedList)
		{
			var controls = 
				control
					.Controls
					.OfType<Control>()
					.Traverse(c => c.Controls.OfType<Control>());

			foreach (var child in controls)
			{
				var child1 = child;

				var objectSerialized = 
					objectSerializedList
						.Where(o => o.ControlId == child1.GetHierarchicalId())
						.SingleOrDefault();

				if (objectSerialized == null)
				{
					continue;
				}

				container
					.Resolve<IObjectSerializer>(child)
					.Load(child, objectSerialized);
			}
		}
	}
}